import RPi.GPIO as GPIO
import time
# 用于读取DS18B20温度传感器数据
import glob
import os

# 定义引脚
LED_PIN_RED = 17
LED_PIN_GREEN = 18
LED_PIN_BLUE = 27
BUZZER_PIN = 22

# 初始化 GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN_RED, GPIO.OUT)
GPIO.setup(LED_PIN_GREEN, GPIO.OUT)
GPIO.setup(LED_PIN_BLUE, GPIO.OUT)
GPIO.setup(BUZZER_PIN, GPIO.OUT)

# 创建 PWM 实例
pwm_red = GPIO.PWM(LED_PIN_RED, 100)
pwm_green = GPIO.PWM(LED_PIN_GREEN, 100)
pwm_blue = GPIO.PWM(LED_PIN_BLUE, 100)
pwm_red.start(0)
pwm_green.start(0)
pwm_blue.start(0)

# 初始化DS18B20传感器
os.system('modprobe w1 - therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'


def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines


def read_temperature():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos + 2:]
        temp_celsius = float(temp_string) / 1000.0
        return temp_celsius


try:
    while True:
        # 读取温度
        temperature = read_temperature()
        # 根据温度计算 LED 亮度（简单映射，可按需调整）
        brightness = min(int((temperature / 50) * 100), 100)

        # 设置三色 LED 亮度
        pwm_red.ChangeDutyCycle(brightness)
        pwm_green.ChangeDutyCycle(brightness)
        pwm_blue.ChangeDutyCycle(brightness)

        # 如果温度过高（比如超过30摄氏度），蜂鸣器发声
        if temperature > 30:
            GPIO.output(BUZZER_PIN, GPIO.HIGH)
        else:
            GPIO.output(BUZZER_PIN, GPIO.LOW)

        time.sleep(1)

except KeyboardInterrupt:
    print("程序被中断，清理 GPIO...")
finally:
    pwm_red.stop()
    pwm_green.stop()
    pwm_blue.stop()
    GPIO.cleanup()